/**
 * @Author: 赵京涛 z19472333952022@163.com
 * @Date: 2024-10-08 09:33:51
 * @LastEditors: 赵京涛 z19472333952022@163.com
 * @LastEditTime: 2024-10-08 09:33:51
 * @projectName: HeBeiHaiYangData
 * @Description: 关于用户及登录的相关数据操作
 */
import { getUserInfo, login, logout } from '@/api/user'
import { resetRouter } from '@/router'
import { getToken, removeToken, setToken } from '@/utils/auth'
import sm2Encrypt from 'sm2js'
import { successMessage, successNotification, useLocalStorage } from '@/hooks'

const getDefaultState = () => {
  return {
    userId: getToken(),
    name: '',
    avatar: '',
    userInfo: ''
  }
}

const state = getDefaultState()
const mutations = {
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState())
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_USERINFO: (state, userInfo) => {
    state.userInfo = userInfo
  },
  SET_USER_TOKEN: (state, userId) => {
    state.userId = userId
  }
}

const actions = {
  // 用户登录
  login({ commit }, userInfo) {
    const { username, password, code } = userInfo
    const cipherMode = 0 // 1 - C1C3C2，0 - C1C2C3，默认为1
    const username1 = sm2Encrypt(username.trim(), process.env.VUE_APP_login_key, cipherMode)
    const password1 = sm2Encrypt(password, process.env.VUE_APP_login_key, cipherMode)
    const code1 = sm2Encrypt(code.trim(), process.env.VUE_APP_login_key, cipherMode)
    return new Promise((resolve, reject) => {
      login({ userId: username1, password: password1, code: code1 })
        .then((response) => {
          const { data } = response
          if (data) {
            commit('SET_USERINFO', data)
            commit('SET_USER_TOKEN', data.userId)
            setToken(data.userId)
            useLocalStorage.setItem('userInfo', JSON.stringify(data))
            useLocalStorage.setItem('token', data.userId)
          }
          resolve(data)
        })
        .catch((error) => {
          reject(error)
        })
    })
  },

  // 获取用户信息
  getUserInfo({ commit }) {
    return new Promise((resolve, reject) => {
      getUserInfo({ userId: getToken() })
        .then((response) => {
          const { data } = response
          if (!data) {
            reject('验证失败，请重新登录！')
          } else {
            useLocalStorage.setItem('userInfo', JSON.stringify(data))
            successNotification('欢迎回来',JSON.parse(useLocalStorage.getItem('userInfo')).userName)
          }
          const { userId } = data
          commit('SET_NAME', userId)
          resolve(data)
        })
        .catch((error) => {
          reject(error)
        })
    })
  },

  // 用户退出
  logout({ state }) {
    return new Promise((resolve, reject) => {
      logout()
        .then(() => {
          // 先清除仓库的用户信息
          removeToken()
          resetRouter()
          useLocalStorage.clear()
          location.reload()
          successMessage('退出成功')
          resolve()
        })
        .catch((error) => {
          reject(error)
        })
    })
  },

  // 删除用户信息
  resetToken({ commit }) {
    return new Promise((resolve) => {
      removeToken()
      useLocalStorage.clear()
      commit('RESET_STATE')
      resolve()
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
